<template>
  <view class="page">
    <!-- 审核环境显示合规内容 -->
    <view v-if="isAuditEnv" class="audit-content">
      <view class="audit-message">
        <text class="audit-icon">🛍️</text>
        <text class="audit-text">校园零食代取与跑腿撮合平台</text>
        <view class="audit-desc">
          <text>· 平台帮助同学发布零食代购/代取需求</text>
          <text>· 不经营商家自营门店，也不提供自营配送</text>
          <text>· 提供订单发布、进度提醒与评价等校园服务</text>
        </view>
        <!-- <view class="audit-tip">完整功能在正式版小程序中面向已审核用户开放。</view> -->
      </view>
    </view>
    
    <!-- 正式环境显示实际功能 -->
    <template v-else>
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input" @click="goToSearch">
        <text class="search-icon">🔍</text>
        <text class="search-placeholder">搜索商品</text>
      </view>
      <view class="cart-icon" @click="goToCart">
        <text class="icon">🛒</text>
        <view class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</view>
      </view>
    </view>

    <!-- 分类栏 -->
    <scroll-view class="category-bar" scroll-x>
      <view 
        class="category-item" 
        v-for="(category, index) in categories" 
        :key="category.id"
        :class="{ active: activeCategory === category.id }"
        @click="switchCategory(category.id)"
      >
        <text class="category-emoji">{{ category.icon }}</text>
        <text class="category-name">{{ category.name }}</text>
      </view>
    </scroll-view>

    <!-- 营业时间和公告栏 -->
    <view class="info-bar">
      <view class="info-item">
        <text class="info-icon">🕐</text>
        <text class="info-text">营业时间：09:00-12:00 / 22:00-24:00</text>
      </view>
      <view class="info-item" v-if="shopNotice">
        <text class="info-icon">📢</text>
        <text class="info-text notice-text">{{ shopNotice }}</text>
      </view>
    </view>

    <!-- 商品列表 -->
    <scroll-view class="product-list" scroll-y lower-threshold="60" @scrolltolower="loadMore">
      <view class="product-grid">
        <view class="product-item" v-for="product in productList" :key="product.id" @click="goToDetail(product)">
          <image 
            class="product-image" 
            :src="product.image || '/static/images/product-default.png'" 
            mode="aspectFill"
            @error="handleImageError"
          ></image>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <view class="product-footer">
              <view class="product-price-box">
                <text class="price-symbol">¥</text>
                <text class="price-value">{{ product.price }}</text>
                <text class="price-original" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
              </view>
              <view class="add-cart-btn" @click.stop="addToCart(product)">
                <text class="add-icon">+</text>
              </view>
            </view>
            <view class="product-tags">
              <text class="tag-hot" v-if="product.sales > 100">🔥 热销</text>
              <text class="tag-stock" v-if="product.stock < 10">仅剩{{ product.stock }}件</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty" v-if="productList.length === 0">
        <image class="empty-image" src="/static/images/empty-product.png" mode="aspectFit"></image>
        <text class="empty-text">暂无商品</text>
      </view>

      <!-- 加载更多 -->
      <view class="loadmore" v-if="productList.length > 0">
        <text class="loadmore-text">{{ loadingText }}</text>
      </view>
    </scroll-view>

    <!-- 购物车悬浮按钮 -->
    <view class="float-cart-btn" @click="goToCart" v-if="cartCount > 0">
      <text class="cart-emoji">🛒</text>
      <view class="cart-count">{{ cartCount }}</view>
    </view>
    </template>
  </view>
</template>

<script>
export default {
  data() {
    return {
      categories: [],
      activeCategory: 0,
      productList: [],
      cartCount: 0,
      page: 1,
      pageSize: 10,
      loading: false,
      finished: false,
      shopNotice: '' // 零食店公告
    }
  },
  computed: {
    loadingText() {
      if (this.loading) return '加载中...'
      if (this.finished) return '没有更多了'
      return '上拉加载更多'
    },
    // 获取审核环境状态
    isAuditEnv() {
      const app = getApp()
      return app.globalData.isAuditEnv || false
    }
  },
  onLoad() {
    this.loadCategories()
    this.loadProducts()
    this.loadCartCount()
    this.loadShopNotice()
  },
  onShow() {
    this.loadCartCount()
  },
  methods: {
    async loadCategories() {
      try {
        const { getCategoryList } = require('@/api/category')
        const categories = await getCategoryList()
        
        // 添加"全部"分类
        this.categories = [
          { id: 0, name: '全部', icon: '🏪' },
          ...(categories || []).map(item => ({
            ...item,
            icon: item.icon || '📦'
          }))
        ]
      } catch (error) {
        console.error('加载分类失败', error)
        // 使用默认分类
        this.categories = [
          { id: 0, name: '全部', icon: '🏪' },
          { id: 1, name: '饮料', icon: '🥤' },
          { id: 2, name: '零食', icon: '🍿' }
        ]
      }
    },
    switchCategory(categoryId) {
      this.activeCategory = categoryId
      this.page = 1
      this.finished = false
      this.productList = []
      this.loadProducts()
    },
    async loadProducts() {
      if (this.loading || this.finished) return
      
      this.loading = true
      
      try {
        const { getProductPage } = require('@/api/product')
        const pageData = await getProductPage({
          categoryId: this.activeCategory,
          current: this.page,
          size: this.pageSize,
          status: 1  // 用户端只查询已上架商品
        })
        
        //console.log('商品分页数据:', pageData)
        
        // MyBatis-Plus 分页对象结构
        const records = pageData.records || []
        
        if (this.page === 1) {
          this.productList = records
        } else {
          this.productList.push(...records)
        }
        
        this.loading = false
        
        // 判断是否还有更多数据
        if (records.length < this.pageSize || this.page >= (pageData.pages || 1)) {
          this.finished = true
        }
      } catch (error) {
        console.error('加载商品失败', error)
        this.loading = false
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },
    loadMore() {
      if (this.loading || this.finished) return
      this.page++
      this.loadProducts()
    },
    loadCartCount() {
      // TODO: 从缓存或API获取购物车数量
      this.cartCount = uni.getStorageSync('cartCount') || 0
    },
    async loadShopNotice() {
      try {
        const { getConfig } = require('@/api/config')
        const notice = await getConfig('snack_shop_announcement')
        this.shopNotice = (notice || '').toString()
      } catch (error) {
        console.error('加载零食店公告失败:', error)
        this.shopNotice = ''
      }
    },
    goToSearch() {
      uni.showToast({ title: '搜索功能开发中...', icon: 'none' })
    },
    goToCart() {
      uni.navigateTo({ url: '/pages/snack/cart' })
    },
    goToDetail(product) {
      uni.navigateTo({ url: `/pages/snack/detail?id=${product.id}` })
    },
    addToCart(product) {
      // 获取购物车
      let cart = uni.getStorageSync('cart') || []
      
      // 查找是否已存在
      const index = cart.findIndex(item => item.productId === product.id)
      
      if (index > -1) {
        // 已存在，增加数量
        const newQuantity = cart[index].quantity + 1
        const maxQuantity = Math.min(product.stock || 99, 99)
        
        if (newQuantity > maxQuantity) {
          uni.showToast({
            title: `最多只能购买${maxQuantity}件`,
            icon: 'none'
          })
          return
        }
        cart[index].quantity = newQuantity
      } else {
        // 不存在，添加新商品
        cart.push({
          productId: product.id,
          name: product.name,
          image: product.image,
          price: product.price,
          quantity: 1,
          stock: product.stock,
          selected: true
        })
      }
      
      // 保存购物车
      uni.setStorageSync('cart', cart)
      
      // 更新购物车数量
      const totalCount = cart.reduce((sum, item) => sum + item.quantity, 0)
      this.cartCount = totalCount
      uni.setStorageSync('cartCount', totalCount)
      
      uni.showToast({ title: '已加入购物车', icon: 'success' })
    },
    handleImageError(e) {
      //console.log('图片加载失败', e)
      // 图片加载失败时显示默认图片
      e.target.src = '/static/images/product-default.png'
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 搜索栏 */
.search-bar {
  background: #fff;
  padding: 20rpx;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;
}

.search-input {
  flex: 1;
  background: #f5f7fa;
  border-radius: 40rpx;
  padding: 20rpx 32rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
  
  .search-icon {
    font-size: 32rpx;
  }
  
  .search-placeholder {
    font-size: 26rpx;
    color: #999;
  }
}

.cart-icon {
  width: 88rpx;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  .icon {
    font-size: 36rpx;
  }
  
  .cart-badge {
    position: absolute;
    top: -4rpx;
    right: -4rpx;
    background: #ff4d4f;
    color: #fff;
    font-size: 20rpx;
    padding: 4rpx 8rpx;
    border-radius: 20rpx;
    min-width: 32rpx;
    text-align: center;
  }
}

/* 分类栏 */
.category-bar {
  background: #fff;
  white-space: nowrap;
  padding: 24rpx 20rpx;
  display: flex;
  gap: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

/* 营业时间和公告栏 */
.info-bar {
  background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
  padding: 16rpx 20rpx;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  
  .info-icon {
    font-size: 28rpx;
    flex-shrink: 0;
  }
  
  .info-text {
    font-size: 24rpx;
    color: #333;
    line-height: 1.4;
    
    &.notice-text {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      line-clamp: 2;
      -webkit-line-clamp: 2;
      overflow: hidden;
      word-break: break-all;
    }
  }
}

.category-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  padding: 0 16rpx;
  
  .category-emoji {
    font-size: 48rpx;
    transition: transform 0.3s;
  }
  
  .category-name {
    font-size: 24rpx;
    color: #666;
    transition: all 0.3s;
  }
  
  &.active {
    .category-emoji {
      transform: scale(1.2);
    }
    
    .category-name {
      color: #667eea;
      font-weight: bold;
    }
  }
}

/* 商品列表 */
.product-list {
  flex: 1;
  height: 0;
  padding: 20rpx;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.product-item {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.product-image {
  width: 100%;
  height: 280rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-info {
  padding: 20rpx;
  position: relative;
}

.product-name {
  font-size: 26rpx;
  color: #333;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  overflow: hidden;
  min-height: 72rpx;
  line-height: 1.4;
  margin-bottom: 12rpx;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price-box {
  display: flex;
  align-items: baseline;
  gap: 4rpx;
  
  .price-symbol {
    font-size: 22rpx;
    color: #ff4d4f;
    font-weight: bold;
  }
  
  .price-value {
    font-size: 32rpx;
    color: #ff4d4f;
    font-weight: bold;
  }
  
  .price-original {
    font-size: 20rpx;
    color: #999;
    text-decoration: line-through;
    margin-left: 8rpx;
  }
}

.add-cart-btn {
  width: 56rpx;
  height: 56rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .add-icon {
    font-size: 32rpx;
    color: #fff;
    font-weight: bold;
  }
}

.product-tags {
  display: flex;
  gap: 12rpx;
  margin-top: 12rpx;
  font-size: 20rpx;
  
  .tag-hot {
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
    color: #fff;
    padding: 4rpx 12rpx;
    border-radius: 8rpx;
  }
  
  .tag-stock {
    background: #fff3e0;
    color: #ff9800;
    padding: 4rpx 12rpx;
    border-radius: 8rpx;
  }
}

/* 悬浮购物车按钮 */
.float-cart-btn {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  
  .cart-emoji {
    font-size: 48rpx;
  }
  
  .cart-count {
    position: absolute;
    top: -8rpx;
    right: -8rpx;
    background: #ff4d4f;
    color: #fff;
    font-size: 20rpx;
    font-weight: bold;
    padding: 8rpx 12rpx;
    border-radius: 24rpx;
    min-width: 40rpx;
    text-align: center;
  }
}

/* 空状态 */
.empty {
  padding: 120rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32rpx;
  
  .empty-image {
    width: 400rpx;
    height: 300rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 加载更多 */
.loadmore {
  padding: 40rpx 20rpx;
  text-align: center;
  
  .loadmore-text {
    font-size: 24rpx;
    color: #999;
  }
}

/* 审核环境显示样式 */
.audit-content {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  padding: 40rpx;
}

.audit-message {
  background: #fff;
  border-radius: 24rpx;
  padding: 80rpx 60rpx;
  text-align: center;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
  max-width: 600rpx;
  
  .audit-icon {
    font-size: 120rpx;
    display: block;
    margin-bottom: 40rpx;
  }
  
  .audit-text {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    display: block;
    margin-bottom: 24rpx;
    line-height: 1.6;
  }
  
  .audit-desc {
    font-size: 28rpx;
    color: #666;
    display: flex;
    flex-direction: column;
    gap: 12rpx;
    width: 100%;
    text-align: left;
    line-height: 1.6;
  }
  
  .audit-tip {
    margin-top: 32rpx;
    font-size: 26rpx;
    color: #999;
    line-height: 1.5;
  }
}
</style>

